﻿package com.badibadi.activity;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.badibadi.activity.UpPicturesActivity.UpPicturesFragment1;
import com.badibadi.adapter.PinLunGYAdapter;
import com.badibadi.fragment.ActivityReadingOffLineFragment;
import com.badibadi.fragment.ActivityReadingOffLineFragment.setActivityView;
import com.badibadi.fragment.ActivityReadingOnLineFragment;
import com.badibadi.fragment.WaterFallFragment_Activityread;
import com.badibadi.fragment.linkActivityFragment;
import com.badibadi.infos.ActivityReadingModel;
import com.badibadi.infos.Activity_SeachModel;
import com.badibadi.infos.Results;
import com.badibadi.infos.User;
import com.badibadi.infos.UserInfoModel;
import com.badibadi.mytools.CalendarTools;
import com.badibadi.mytools.CommonUtils;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.Dialog;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.ShareSDKTools;
import com.badibadi.mytools.TabHostUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.serializable.PostActivityData;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.SinaExpressionActivity;
import com.libjph.util.StringUtil;
import com.view.my_view.MyWebView_ShowAll;

//ShareSDK
//后来改了    只需要传入一个actId就行了 joinbtn ok
public class ActivityReadingActivity extends BaseActivity implements
		OnClickListener {

	private TabHost mTabHost;
	private LinearLayout activity_layout;
	private PopupWindow pop;
	private FragmentManager manager;
	private ActivityReadingOffLineFragment activityReadingFragment;
	private ActivityReadingOnLineFragment activityReadingOnLineFragment;
	private PostActivityData postActivityData;
	private WaterFallFragment_Activityread fragment1;
	// 相关活动
	private linkActivityFragment linkfragment;

	private boolean isOnLine;
	private UserInfoModel userInfoModel;

	static ActivityReadingActivity instens;
	private ActivityReadingModel activityReadingModel = null;
	public boolean isRun = true;// 更新标题的线程
	public String KEY0 = "title";
	public TextView tv_title;
	private String actId;// 活动的id
	private String activity_faqi_uid;// 活动发起者的id
	private String uid;

	private String cid;// 俱乐部的id(仅用于分享，选传,从上一个界面传入)

	// private WaterFallFragment waterFallFragment;

	// RelativeLayout up_picture;
	RelativeLayout Join;

	Button joinbtn;
	Button Share;
	LinearLayout activityRootView;
	private String act_name;// 活动名字

	/** 活动的查询好的内容 */
	public Activity_SeachModel seachModel;
	private Handler handler = new Handler() {
		@SuppressLint("NewApi")
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(ActivityReadingActivity.this);
				try {
					tv_title.setText("" + activityReadingModel.getNames());

					Share.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							if (!Utils.getUid(ActivityReadingActivity.this)
									.equals("")) {
								if (activityReadingModel.getIntroduce()
										.length() > 120) {
									String content = activityReadingModel
											.getIntroduce().substring(0, 120)
											+ "...";

									if (!StringUtil
											.isNullOrEmpty(activityReadingModel
													.getImage())) {
										ShareSDKTools
												.ShowOneKeyShare(
														ActivityReadingActivity.this,
														"分享",
														content,
														"",
														Constants.BadiDownImgUrl
																+ "/"
																+ activityReadingModel
																		.getImage()
																+ Constants.Appactivitycover,
														"activity",
														activityReadingModel
																.getId(),
														activityReadingModel
																.getUid(), cid,
														"activity");
									} else {
										ShareSDKTools.ShowOneKeyShare(
												ActivityReadingActivity.this,
												"分享", content, "", "",
												"activity",
												activityReadingModel.getId(),
												activityReadingModel.getUid(),
												cid, "activity");
									}

								} else {
									String content = activityReadingModel
											.getIntroduce().toString();
									if (!StringUtil
											.isNullOrEmpty(activityReadingModel
													.getImage())) {
										ShareSDKTools
												.ShowOneKeyShare(
														ActivityReadingActivity.this,
														"分享",
														content,
														"",
														Constants.BadiDownImgUrl
																+ "/"
																+ activityReadingModel
																		.getImage()
																+ Constants.Appactivitycover,
														"activity",
														activityReadingModel
																.getId(),
														activityReadingModel
																.getUid(), cid,
														"activity");
									} else {
										ShareSDKTools.ShowOneKeyShare(
												ActivityReadingActivity.this,
												"分享", content, "", "",
												"activity",
												activityReadingModel.getId(),
												activityReadingModel.getUid(),
												cid, "activity");
									}
								}
							} else {
								Utils.showMessage(
										ActivityReadingActivity.this,
										getResources().getString(
												R.string.l_xb10));
							}

						}
					});

					if (activityReadingModel.getIs_atend().equals("1"))// 是否参加过该活动
					{
						ChangeJoinOrNoJoinActivity(true);
					} else {
						ChangeJoinOrNoJoinActivity(false);
						joinbtn.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								ChangeJoinOrNoJoinActivity(false);

								if (!Utils.getUid(ActivityReadingActivity.this)
										.equals("")) {

									if (seachModel.getStatus().equals("1")) {
										settingJoinPopWindow();
									} else if (seachModel.getStatus().equals(
											"2")) {
										Utils.showMessage(
												ActivityReadingActivity.this,
												getResources().getString(
														R.string.wx_txt_106));
									}
								} else {
									Utils.showMessage(
											ActivityReadingActivity.this,
											getResources().getString(
													R.string.l_xb10));
								}

							}
						});// 参加了就上传图片
					}
				} catch (Exception e) {
				}
				break;
			case 2:// 网络错误
				Utils.ExitPrgress(ActivityReadingActivity.this);
				Utils.showMessage(ActivityReadingActivity.this, getResources()
						.getString(R.string.l_net_error));
				break;
			case 3:// 提交成功
				Utils.ExitPrgress(ActivityReadingActivity.this);
				try {
					Utils.showMessage(ActivityReadingActivity.this,
							getResources().getString(R.string.l_xb11));
					Intent intent = new Intent(ActivityReadingActivity.this,
							ActivityReadingActivity.class);
					intent.putExtra("actId", actId);
					startActivity(intent);
					finish();
				} catch (Exception e) {
				}
				break;
			case 4:// 系统出错
				Utils.ExitPrgress(ActivityReadingActivity.this);
				Utils.showMessage(ActivityReadingActivity.this, getResources()
						.getString(R.string.l_xb12));
				break;
			case 5:// 申请失败
				Utils.ExitPrgress(ActivityReadingActivity.this);
				try {
					Utils.showMessage(
							ActivityReadingActivity.this,
							msg.getData().getString("msg",
									getResources().getString(R.string.l_xb13)));
				} catch (Exception e) {
				}
				break;
			case 6:
				Utils.ExitPrgress(ActivityReadingActivity.this);
				try {
					activity_faqi_uid = seachModel.getUid();
					cid = seachModel.getCid();
					String ss = seachModel.getIs_online();
					if (ss.equals("1")) {
						isOnLine = true;
					} else {
						isOnLine = false;
					}
					init();
				} catch (Exception e) {
				}

				break;
			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		/* requestWindowFeature(featureId); */
		setContentView(R.layout.activity_activity_reading);
		tv_title = (TextView) findViewById(R.id.title);
		Share = (Button) ActivityReadingActivity.this.findViewById(R.id.Share);
		instens = ActivityReadingActivity.this;

		actId = getIntent().getStringExtra("actId");
		actIdToInfo(actId);
		settingTabHost();
		uid = Utils.getUid(ActivityReadingActivity.this);
		RefreshDataThread(uid);
	}

	/**
	 * 根据活动id找活动发起者id和活动的俱乐部id和线上活动还是线下活动---POST
	 * 
	 * @param $actId
	 *            ---活动ID
	 */
	private void actIdToInfo(final String actId2) {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				MyThreadTool.fixedThreadPool.execute(new Runnable() {
					@Override
					public void run() {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("uid",
								Utils.getUid(ActivityReadingActivity.this));
						map.put("actId", actId2);
						String content = null;

						content = Utils.sendRequest(map, Constants.BadiUrl_1
								+ "commonality/actIdToInfo");
						//
						if (content != null) {
							Results results = Utils.checkResult_NNN(
									ActivityReadingActivity.this, content);

							//

							if (results != null
									&& !results.getRetmsg().equals("null")) {

								try {
									if (results.isRet() == true) {
										seachModel = JSONUtils.getEntityByJsonString(
												results.getRetmsg(),
												Activity_SeachModel.class);
										handler.sendEmptyMessage(6);
									} else {
										handler.sendEmptyMessage(2);
									}

								} catch (Exception e) {

								}
							} else {
								handler.sendEmptyMessage(2);
							}
						} else {
							handler.sendEmptyMessage(1);
						}
					}
				});
			}
		});
	}

	private void init() {
		if (cid == null) {
			cid = "0";
		}
		if (postActivityData != null) {
			isOnLine = postActivityData.isLine();
		} else if (postActivityData == null) {
		}

		manager = getSupportFragmentManager();
		activity_layout = (LinearLayout) this
				.findViewById(R.id.activity_reading_layout);

		if (isOnLine == true) {
			LoadFragment(0);
		} else {
			LoadFragment(3);
		}
		Join = (RelativeLayout) this.findViewById(R.id.Join);
		joinbtn = (Button) this.findViewById(R.id.joinbtn);
		this.findViewById(R.id.activity_back).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						ActivityReadingActivity.this.finish();
					}
				});
	}

	/**
	 * 一个popWindow
	 */
	public void settingJoinPopWindow() {// address
		View view = this.getLayoutInflater().inflate(
				R.layout.activity_reading_popwindows, null);
		if (activityReadingModel != null) {
			TextView startTimeAddEndTime = (TextView) view
					.findViewById(R.id.startTimeAddEndTime);
			// 开始和结束时间
			String start = CalendarTools.getFormatTime(
					Double.parseDouble(activityReadingModel.getStart_time()
							+ "000"), "yyyy.MM.dd HH.mm");
			String end = CalendarTools.getFormatTime(
					Double.parseDouble(activityReadingModel.getEnd_time()
							+ "000"), "yyyy.MM.dd HH.mm");
			startTimeAddEndTime.setText(start + "-" + end);
			// 地址
			if (activityReadingModel.getAddress() != null) {
				TextView address = (TextView) view.findViewById(R.id.address);
				if (activityReadingModel.getIs_online().equals("1"))// is_online
				{
					address.setText(""
							+ getResources().getString(R.string.OnlineTheme));
				} else {
					address.setText("" + activityReadingModel.getAddress());
				}

			}
			// 活动名称
			if (activityReadingModel.getNames() != null) {
				TextView names = (TextView) view.findViewById(R.id.names);
				names.setText("" + activityReadingModel.getNames());
			}
			// 种类
			if (activityReadingModel.getTypeName() != null) {
				TextView type = (TextView) view.findViewById(R.id.type);
				type.setText("" + activityReadingModel.getTypeName().getName());
			}
			// 参加活动所需金币
			if (activityReadingModel.getGold() != null) {
				TextView gold = (TextView) view.findViewById(R.id.gold);
				gold.setText("" + activityReadingModel.getGold());
			}
			// 已经参加的人数
			if (activityReadingModel.getApplied() != null) {
				TextView Joinnum = (TextView) view.findViewById(R.id.Joinnum);
				Joinnum.setText("" + activityReadingModel.getApplied());
			}
			// 确定参加活动
			view.findViewById(R.id.ok).setOnClickListener(
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							if (activityReadingModel.getIs_online().equals("0")) {
								System.out.println(userInfoModel.getPhone());
								if (!(userInfoModel.getPhone().equals(""))
										&& !(userInfoModel.getEmail()
												.equals(""))) {
									Dialog dialog = new Dialog();
									dialog.CreateDialog(
											ActivityReadingActivity.this,
											getResources().getString(
													R.string.l_xb14),
											getResources().getString(
													R.string.l_xb15)
													+ activityReadingModel
															.getGold()
													+ getResources().getString(
															R.string.l_xb16));
									dialog.setOnDialogClistener(new Dialog.DialogClistener() {

										@Override
										public void ret() {

										}

										@Override
										public void ok() {
											add_activity(activityReadingModel
													.getId());

										}
									});
									pop.dismiss();
								} else {

									Toast toast;
									toast = Toast
											.makeText(
													getApplicationContext(),
													getResources()
															.getString(
																	R.string.email_and_phone_is_required),
													100);
									toast.setGravity(Gravity.CENTER, 0, 0);
									toast.show();
									Intent intent = new Intent(
											ActivityReadingActivity.this,
											MyDataActivity.class);
									intent.putExtra(
											"uid",
											Utils.getUid(ActivityReadingActivity.this));
									startActivity(intent);
								}
							} else {

								Dialog dialog = new Dialog();
								dialog.CreateDialog(
										ActivityReadingActivity.this,
										getResources().getString(
												R.string.l_xb14),
										getResources().getString(
												R.string.l_xb15)
												+ activityReadingModel
														.getGold()
												+ getResources().getString(
														R.string.l_xb16));
								dialog.setOnDialogClistener(new Dialog.DialogClistener() {

									@Override
									public void ret() {

									}

									@Override
									public void ok() {
										add_activity(activityReadingModel
												.getId());

									}
								});
								pop.dismiss();

							}
						}
					});

		}

		view.findViewById(R.id.Cancle).setOnClickListener(this);

		pop = new PopupWindow(view, (int) getScreenSize(SCREENW),
				(int) getScreenSize(SCREENH) * 2 / 3);
		PopSetting(pop);
		pop.setWidth(LayoutParams.MATCH_PARENT);
		pop.setHeight(LayoutParams.WRAP_CONTENT);
		pop.showAtLocation(findViewById(R.id.activity_reading_layout),
				Gravity.BOTTOM, 0, 0);

	}

	/**
	 * 用户申请参加活动 接口
	 * 
	 * @param $uid
	 *            ;//用户id @param $aid;//活动id
	 */
	public void add_activity(String aid) {
		String uid = Utils.getUid(ActivityReadingActivity.this);
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("uid", uid);
		obj.put("aid", aid);

		CommonUtils.CommomPostfunction(ActivityReadingActivity.this,
				Constants.BadiUrl_1 + "/" + "Index/add_activity", obj, handler,
				2, 4, 3, 5);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.Cancle:
			pop.dismiss();
			break;

		}
	}

	private void settingTabHost() {
		mTabHost = (TabHost) this.findViewById(R.id.activity_reading_tabhost);
		mTabHost.setup();
		mTabHost.addTab(mTabHost
				.newTabSpec("activityReading one")
				.setIndicator(getResources().getString(R.string.Content),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab1));
		mTabHost.addTab(mTabHost
				.newTabSpec("activityReading two")
				.setIndicator(getResources().getString(R.string.picture),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab2));
		// dust 添加地图显示
		mTabHost.addTab(mTabHost
				.newTabSpec("activityReading fore")
				.setIndicator(
						getResources().getString(R.string.RelatedActivities),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab3));
		TabHostUtils.SetTabHost(ActivityReadingActivity.this, mTabHost);
		mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {

			@Override
			public void onTabChanged(String tabId) {

				switch (mTabHost.getCurrentTab()) {
				case 0:
					if (isOnLine == true)
						LoadFragment(0);
					else
						LoadFragment(3);

					break;
				case 1:
					LoadFragment(1);
					break;
				case 2:
					LoadFragment(2);
					break;
				}
			}
		});

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		uid = Utils.getUid(ActivityReadingActivity.this);
		RefreshDataThread(uid);
	}

	/**
	 * 读取fragment
	 * 
	 */
	public void LoadFragment(int num) {
		FragmentTransaction transaction = manager.beginTransaction();
		switch (num) {
		case 0:// 线上
			activityReadingOnLineFragment = new ActivityReadingOnLineFragment();
			Bundle bundle = new Bundle();
			bundle.putInt("activityRootView", R.id.activityRootView);
			bundle.putString("actId", actId);
			bundle.putString("fq_uid", activity_faqi_uid);
			bundle.putString("cid", cid);
			activityReadingOnLineFragment.setArguments(bundle);
			transaction.replace(R.id.activity_reading_layout,
					activityReadingOnLineFragment);
			transaction.commit();
			panduanIs_JoinActivity_OnLine();
			break;
		case 1:// 图片
				// System.out.println(activityReadingModel);//dust查看图片信息
			try {
				act_name = activityReadingModel.getNames();
			} catch (Exception e) {
				// TODO: handle exception
			}

			fragment1 = WaterFallFragment_Activityread.getInstance();
			Bundle bundle2 = new Bundle();
			bundle2.putString("actId", actId);
			bundle2.putString("is_joined", activityReadingModel.getIs_atend());
			bundle2.putString("fq_uid", activity_faqi_uid);
			if (act_name != null) {
				bundle2.putString("act_name", act_name);
			}
			if (!StringUtil.isNullOrEmpty(cid) && !cid.equals("0")) {
				bundle2.putString("cid", cid);
			}
			fragment1.setArguments(bundle2);
			transaction.replace(R.id.activity_reading_layout, fragment1);
			transaction.commit();
			//
			break;
		case 2:// 相关活动
			linkfragment = linkActivityFragment.getInstance();
			// linkfragment.setArguments(bundle);''
			Bundle bundle4 = new Bundle();
			bundle4.putString("actId", actId);
			linkfragment.setArguments(bundle4);
			//
			transaction.replace(R.id.activity_reading_layout, linkfragment);
			transaction.commit();

			break;
		case 3:// 线下
			activityReadingFragment = new ActivityReadingOffLineFragment();
			Bundle bundle3 = new Bundle();
			bundle3.putString("actId", actId);
			bundle3.putString("fq_uid", activity_faqi_uid);
			bundle3.putString("cid", cid);
			// bundle3.putInt("activityRootView", R.id.activityRootView);
			activityReadingFragment.setArguments(bundle3);
			transaction.replace(R.id.activity_reading_layout,
					activityReadingFragment);
			transaction.commit();
			panduanIs_JoinActivity();
			break;

		}
	}

	/**
	 * 用于判断是否参加过该活动（线上）
	 */
	public void panduanIs_JoinActivity_OnLine() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (activityReadingModel == null) {
					//
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {

					}

					activityReadingOnLineFragment
							.getData(new ActivityReadingOnLineFragment.setActivityView() {

								@Override
								public void getData(
										ActivityReadingModel activityModel) {
									if (activityModel != null) {
										activityReadingModel = activityModel;
										handler.sendEmptyMessage(1);
									}

								}
							});
				}

			}
		}).start();
	}

	/**
	 * 用于判断是否参加过该活动（线下）
	 */
	public void panduanIs_JoinActivity() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (activityReadingModel == null) {
					//
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {

					}

					activityReadingFragment.getData(new setActivityView() {

						@Override
						public void getData(ActivityReadingModel activityModel) {
							if (activityModel != null) {
								activityReadingModel = activityModel;
								handler.sendEmptyMessage(1);
							}

						}
					});

				}

			}
		}).start();
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, final Intent arg2) {
		// 这是接受表情的
		if (arg0 == PinLunGYAdapter.BIAO_QING
				&& arg1 == SinaExpressionActivity.ACTIVITY_BIAOQING) {
			if (arg2 != null) {
				if (isOnLine == true) {
					activityReadingOnLineFragment
							.getSend_Content(new ActivityReadingOnLineFragment.getEditText() {

								@Override
								public void getEditText(EditText send_content) {
									if (send_content != null) {

										String content2 = arg2
												.getStringExtra("result");
										int index = send_content
												.getSelectionStart();
										Editable edit = send_content
												.getEditableText();
										edit.insert(index, content2);

									}
								}
							});
				} else {
					activityReadingFragment
							.getSend_Content(new ActivityReadingOffLineFragment.getEditText() {

								@Override
								public void getEditText(EditText send_content) {
									if (send_content != null) {
										String content2 = arg2
												.getStringExtra("result");
										int index = send_content
												.getSelectionStart();
										Editable edit = send_content
												.getEditableText();
										edit.insert(index, content2);
									}
								}
							});
				}
			}
		}

		super.onActivityResult(arg0, arg1, arg2);
	}

	/**
	 * 交换参加和上传按钮
	 * 
	 * @param is_Join
	 *            （没参加是参加按钮，参加后是上传图片按钮）
	 */
	public void ChangeJoinOrNoJoinActivity(boolean is_Join) {
		if (is_Join == true) {
			// up_picture.setVisibility(View.VISIBLE);
			Join.setVisibility(View.GONE);
		} else {
			// up_picture.setVisibility(View.GONE);
			Join.setVisibility(View.VISIBLE);
		}

	}

	public interface Switch_Fragment {

	}

	public void RefreshDataThread(final String uid) {
		
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub

				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", uid);
				map.put("languageType", com.badibadi.mytools.Dialog
						.getSystemLanguageType(ActivityReadingActivity.this));
				String content = Utils.sendRequest(map, Constants.BadiUrl
						+ "userDataShow");
				if (content != null) {
					// ("结果是:" + content);
					Results results = Utils.checkResult_NNN(
							ActivityReadingActivity.this, content);
					if (results != null && results.getRetmsg() != null) {
						//
						// ("得到的结果是：" + results.getRetmsg());
						try {
							userInfoModel = JSONUtils.getEntityByJsonString(
									results.getRetmsg(), UserInfoModel.class);
							userInfoModel.setUid(uid);
							System.out.println("userInfoModelaaaaaaa"
									+ results.getRetmsg());
							// handler.sendEmptyMessage(4);
						} catch (JSONException e) {
							// ("解析出错");

						} catch (Exception e) {
							// TODO Auto-generated catch block
							//

						}
					} else {

					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}
}
